package com.lh.controller;

import com.lh.config.constant.GlobalConstant;
import com.lh.core.annotation.Authorization;
import com.lh.core.annotation.CurrentUser;
import com.lh.entity.table.DsmsUser;
import com.lh.entity.vo.TokenModel;
import com.lh.service.DsmsUserService;
import com.lh.service.TokenManager;
import com.lh.utils.Answer;
import com.lh.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class TokenController {

    @Autowired
    private DsmsUserService dsmsUserService;
    @Resource
    private TokenManager tokenManager;
    @Resource
    private RedisUtil redisUtil;

    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public Answer<TokenModel> login(@RequestParam String username,@RequestParam String password){

        DsmsUser user =  dsmsUserService.login(username, password);
        //生成一个token，保存用户登录状态
        TokenModel model = tokenManager.get(user.getId());
        if (model == null) {
            model = tokenManager.createToken(user.getId());
        }

        // 存储user
        String token = model.getUserId() + "_" + model.getToken();
        redisUtil.set(token, user, GlobalConstant.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return Answer.ok(model);
    }

    /**
     * 第三方登录获取用户信息
     */


    /**
     * 注销
     */
    @Authorization
    @RequestMapping(method = RequestMethod.DELETE)
    public Answer<Object> logout(@CurrentUser DsmsUser user) {

        tokenManager.deleteToken(user.getId());

        return Answer.ok("注销成功");
    }


}